package com.Qinmeiwei.web.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Constants {
	
	private static final Logger log = LoggerFactory.getLogger(Constants.class);
	
	private static Constants instance;

	/** 工程实际所在物理路径 */
	public static String WEB_ROOT;

	/** 应用上下文路径 */
	public static String CONTEXT_PATH;
	
	/** 资源文件路径（相对或绝对URL）*/
	public static String RESOURCE_ROOT;
	
	/** 文件上传物理路径*/
	public static String UPLOAD_PATH;
	
	/** 文档访问基准URL */
	public static String DOC_BASE_URL;
	
	/** ajax请求返回的结果页面 */
	public static String AJAX_RESULT = "commons/ajaxJSONResult";

	/** ajax请求结果在上下文中的KEY名 */
	public static final String AJAX_RESULT_KEY = "json";

	public static String CSS = "styles";
	
	public static String JS = "scripts";
	
	public static String IMG = "images";

	@Value("#{constant.isDebugMode}")
	public boolean isDebugMode = false;
	
	public static Constants getInstance() {
		if (instance != null)
			return instance;
		else
			throw new IllegalArgumentException("Please create instance of Constants.class by Spring!");
	}

	private Constants() {}

	@Value("#{constant.resource_root}")
	public void setResourceRoot(String resourceRoot){
		if(resourceRoot.startsWith("/")){
			Constants.RESOURCE_ROOT = Constants.CONTEXT_PATH + resourceRoot;
		}else{
			if(resourceRoot.toLowerCase().startsWith("http")){
				Constants.RESOURCE_ROOT = resourceRoot;
			}else{
				Constants.RESOURCE_ROOT = Constants.CONTEXT_PATH + "/" + resourceRoot;
			}
		}
		
		Constants.JS = RESOURCE_ROOT + "/" + JS;
		Constants.CSS = RESOURCE_ROOT + "/" + CSS;
	}
	
	@Value("#{constant.upload_path}")
	public void setUploadPath(String uploadPath) {
		if (uploadPath.startsWith("$WEB_ROOT/"))
			Constants.UPLOAD_PATH = uploadPath.replace("$WEB_ROOT/", WEB_ROOT);
		else {
			Constants.UPLOAD_PATH = uploadPath;
		}
	}
	
	@Value("#{constant.doc_base_url}|#{constant.upload_path}|/#{constant.upload_office_dir}")
	public void setDocBaseUrl(String value){
		Constants.DOC_BASE_URL = Constants.CONTEXT_PATH+"/upload/officeFile";
		if(StringUtils.isNotEmpty(value)){
			String[] v = StringUtils.split(value, "|");
			if("/".equals(v[0]) && v[1].startsWith("$WEB_ROOT")){
				Constants.DOC_BASE_URL = v[1].replace("$WEB_ROOT", Constants.CONTEXT_PATH)+v[2];
				return;
			}else if(v[0].startsWith("http://")){
				Constants.DOC_BASE_URL = v[0]+v[2];
				return;
			}
		}
		log.error("# Error config value for doc_base_url in Constants.properties");
	}
	
}
